package com.example.helloword.controller;

import com.example.helloword.dao.DepartmentDao;
import com.example.helloword.dao.EmployeeDao;
import com.example.helloword.pojo.Department;
import com.example.helloword.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;

/**
 * @create 2022-03-2022/3/10-19:35
 */
@Controller
public class EmployeeController {

    @Autowired
    EmployeeDao employeeDao;

    @Autowired
    DepartmentDao departmentDao;

    @RequestMapping("/employees")
    public String getList(Model model){
       Collection<Employee> employees= employeeDao.getAllEmployee();
       model.addAttribute("emp",employees);
       //model.addAllAttributes("employesss",employees);
       return "employee/list";
    }

    //添加
    @GetMapping("/addEmployee")
    public String goToAddPage( Model model){
        //查出所有部门信息
        Collection<Department> departments= departmentDao.getAllDepartment();
        model.addAttribute("depmts",departments);
        return "employee/add";
    }
    @PostMapping("/addEmployee")
    public String addEmployee(Employee employee){
        System.out.println(employee);
        employeeDao.saveEmployee(employee);

        return "redirect:/employees";//重定向
    }


    //修改
    @GetMapping("/updateEmployee/{id}")
    public String goToUpdatePage(Model model, @PathVariable("id") Integer id){
        Employee employee=employeeDao.getEmployeeById(id);
        model.addAttribute("nowEmployee",employee);
        Collection<Department> departments= departmentDao.getAllDepartment();
        model.addAttribute("depmts",departments);
        return "employee/update";
    }
    @PostMapping("/updateEmployee")
    public String updateEmployee(Employee employee){
        employeeDao.saveEmployee(employee);
        return "redirect:/employees";//重定向
    }


    //删除
    @RequestMapping("deleteEmployee/{id}")
    public String deleteEmployee(@PathVariable("id") Integer id,Model model){
        employeeDao.deleteById(id);
        Collection<Department> departments= departmentDao.getAllDepartment();
        model.addAttribute("depmts",departments);
        return "redirect:/employees";//重定向

    }
}
